package br.com.vti.leilao.controller;

import br.com.vti.leilao.model.entity.Leilao;
import br.com.vti.leilao.model.entity.Usuario;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.CopyOnWriteArraySet;
import javax.servlet.http.HttpServletRequest;
import org.apache.catalina.websocket.StreamInbound;
import org.apache.catalina.websocket.WebSocketServlet;
import org.apache.log4j.Logger;
import org.springframework.security.core.Authentication;

/**
 *
 * @author ednardomatos
 */
public class ConexaoSocketServlet extends WebSocketServlet {
    
    private static final long serialVersionUID = -1813338384737253403L;
    
    public transient static final Logger logger = Logger.getLogger(ConexaoSocketServlet.class);

    private final Set<Conexao> conexoes = new CopyOnWriteArraySet<Conexao>();
    
    public Set<Conexao> getConexoes() {
        return conexoes;
    }

    @Override
    protected StreamInbound createWebSocketInbound(String string, HttpServletRequest hsr) {
        return new Conexao(conexoes, getUsuarioLogado(hsr), getIdLeilao(hsr));
    }

    private Integer getIdLeilao(HttpServletRequest hsr) throws NumberFormatException {
        Integer idLeilao = null;
        String parameter = hsr.getParameter("id");
        if (parameter != null) {
            idLeilao = Integer.parseInt(parameter);
        }
        return idLeilao;
    }

    private Usuario getUsuarioLogado(HttpServletRequest hsr) {
        Usuario usuario = null;
        if (hsr != null) {
            Authentication auth = (Authentication) hsr.getUserPrincipal();
            if (auth != null) {
                usuario = (Usuario) auth.getPrincipal();
            }
        }
        return usuario;
    }

}
